/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package roles;

import avenue.MyWindowEvent;
import avenue.messageBox;
import java.awt.Color;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import users.*;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Module;
import model.RolePermission;
import model.UserRole;

/**
 *
 * @author Aggelos
 */
public class EditRoleForm extends javax.swing.JFrame {
    private EditRoleForm thisFrame;

    /**
     * Creates new form EditUserForm
     */
    public EditRoleForm() {
        em = DBManager.em;
        initComponents();
         getContentPane().setBackground(Color.white);
        //Στοιχιση στο κέντρο 24/2/2013
        setLocationRelativeTo(null);
    }
    
     public EditRoleForm(UserRole ur, boolean readOnly) {
        em = DBManager.em;
        userRole1=ur;
        this.readOnly = readOnly;
        initComponents();
         getContentPane().setBackground(Color.white);
        //Στοιχιση στο κέντρο 24/2/2013
        setLocationRelativeTo(null);
   //     this.getToolkit().getSystemEventQueue().postEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        userRole2 = userRole1;
        query1 = em.createQuery("select rp from RolePermission rp where rp.roleId=:userRole").setParameter("userRole",userRole2);
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        roleBoxRenderer1 = new avenue.RoleBoxRenderer();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jTextField1 = new javax.swing.JTextField();
        Save = new javax.swing.JButton();
        Cancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        neo = new javax.swing.JButton();
        edit = new javax.swing.JButton();
        del = new javax.swing.JButton();

        roleBoxRenderer1.setText("roleBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setState(getDefaultCloseOperation());

        jLabel1.setText("Όνομα Ρόλου : ");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRole2, org.jdesktop.beansbinding.ELProperty.create("${roleName}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        Save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        Save.setText("Αποθήκευση");
        Save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveActionPerformed(evt);
            }
        });

        Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        Cancel.setText("Ακυρο");
        Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelActionPerformed(evt);
            }
        });

        JCheckBox checkBoxCC = new javax.swing.JCheckBox();
        JCheckBox checkBoxCD = new javax.swing.JCheckBox();
        JCheckBox checkBoxCR = new javax.swing.JCheckBox();
        JCheckBox checkBoxCU = new javax.swing.JCheckBox();
        jTable1.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list1, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${moduleId.description}"));
        columnBinding.setColumnName("Module ");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canCreate}"));
        columnBinding.setColumnName("Can Create");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canDelete}"));
        columnBinding.setColumnName("Can Delete");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canRetrieve}"));
        columnBinding.setColumnName("Can Retrieve");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canUpdate}"));
        columnBinding.setColumnName("Can Update");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationLevelAccess}"));
        columnBinding.setColumnName("Station Level Access");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.getColumn("Can Create").setCellEditor(new DefaultCellEditor(checkBoxCC));
        jTable1.getColumn("Can Delete").setCellEditor(new DefaultCellEditor(checkBoxCD));
        jTable1.getColumn("Can Retrieve").setCellEditor(new DefaultCellEditor(checkBoxCR));
        jTable1.getColumn("Can Update").setCellEditor(new DefaultCellEditor(checkBoxCU));
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(120);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(3).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(4).setResizable(false);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(5).setResizable(false);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(50);

        neo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/world_add.png"))); // NOI18N
        neo.setText("Νέο");
        neo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                neoActionPerformed(evt);
            }
        });

        edit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/world_edit.png"))); // NOI18N
        edit.setText("Επεξεργασία");
        edit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editActionPerformed(evt);
            }
        });

        del.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/world_delete.png"))); // NOI18N
        del.setText("Διαγραφή");
        del.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 820, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(neo, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(edit, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(del, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Save, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(Cancel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(neo)
                            .addComponent(del)
                            .addComponent(edit))
                        .addGap(13, 98, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(Save)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Cancel)
                        .addContainerGap())))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelActionPerformed
        //Ενέργειες που εκτελούντε όταν πατάμε άκυρο
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
       }
       //this.setVisible(false); 
       dispose(); 
    }//GEN-LAST:event_CancelActionPerformed

    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveActionPerformed
        //Ενέργειες που εκτελούντε όταν πατάμε άποθηκευση

        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,true);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
       }
       this.setVisible(false); 
    }//GEN-LAST:event_SaveActionPerformed

    private void neoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_neoActionPerformed
        // ενέργειες που εκτελούντε όταν πατάμε Νέο
        final RolePermission rp = new RolePermission();
        rp.setRoleId(userRole2);
        Query modQuery = em.createNamedQuery("Module.findAll", Module.class);
        List<Module> modList = modQuery.getResultList();// φορτώνουμε την λίστα με τα Module
        Query uRolPerQuery = em.createQuery("select rp from RolePermission rp where rp.roleId=:roleId").setParameter("roleId", ur);
        List<RolePermission> rolPerList = uRolPerQuery.getResultList(); //φορτώνουμε την λίστα των δικαιωμάτων του ρόλου 
        if(modList.size() == rolPerList.size())
        { //Εάν στον ρόλο έχουμε προσθέσει όλα τα δικαιωματα εμφανίζει μηνυμα
           messageBox.infoBox("Δεν μπορεί να προστεθεί άλλο Module");
        }
        else  
        {//Εάν δεν έχει όλα τα δικαιώματα φορτώνει την φόρμα επεξεργασίας Module με παράμετρο true που σημαίνει εισαγωγή νέου MODULE
            EditModuleForm emf = new EditModuleForm(rp,true);
            emf.setVisible(true);
            thisFrame=this;
            thisFrame.setEnabled(false);

            //************
             emf.addWindowListener(new WindowListener() {
                 public void windowClosed(WindowEvent arg0) {
                     System.out.println("Window close event occur");
                    if (((MyWindowEvent)arg0).exitAndSave){                                      
                         list1.add(rp);
                         int row = list1.size() - 1;     
                         em.getTransaction().commit();
                         em.getTransaction().begin();
                         em.persist(rp);
                         jTable1.setRowSelectionInterval(row, row);
                         jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
                         thisFrame.setEnabled(true);
                     }
                     else{
                         thisFrame.setEnabled(true);
                         em.getTransaction().rollback();
                         em.getTransaction().begin();
                         java.util.Collection data = query1.getResultList();
                         for (Object entity : data) {
                         em.refresh(entity);
                         }
                         list1.clear();
                         list1.addAll(data);
                     }
                 }
                 public void windowActivated(WindowEvent arg0) {
                     System.out.println("Window Activated");
                 }
                 public void windowClosing(WindowEvent arg0) {
                     System.out.println("Window Closing");
                 }
                 public void windowDeactivated(WindowEvent arg0) {
                     System.out.println("Window Deactivated");
                 }
                 public void windowDeiconified(WindowEvent arg0) {
                     System.out.println("Window Deiconified");
                 }
                 public void windowIconified(WindowEvent arg0) {
                     System.out.println("Window Iconified");
                 }
                 public void windowOpened(WindowEvent arg0) {
                     System.out.println("Window Opened");
                 }
             });
        }
    }//GEN-LAST:event_neoActionPerformed

    private void editActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editActionPerformed
        // ενεργειες που εκτελούντε όταν πατάμε επεξεργασία
       s=jTable1.getSelectedRow();
        
        if (s>=0) {//Ελέγχουμε αν έχουμε κάνει επιλογή στον πίνακα
            
            rp = list1.get(jTable1.getSelectedRow());
                em.persist(rp);// φαίρνει την οντότητα σε κατάσταση διαχείρισης
                //φορτώνει την φόρμα επεξεργασίας Module με παράμετρο false που σημαίνει εισαγωγή νέου MODULE
                EditModuleForm emf = new EditModuleForm(rp,false);
                  emf.setVisible(true);
                  thisFrame=this;
                 thisFrame.setEnabled(false);
        
       
       //************
        emf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    list1.set(s,rp);
                    jTable1.setRowSelectionInterval(s, s);
                    jTable1.scrollRectToVisible(jTable1.getCellRect(s, 0, true));
                     System.out.println("Window close event occur again");
                    em.persist(rp);
                    thisFrame.setEnabled(true);
                    
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                    em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        }
     // Εαν δεν έχουμε κάνει επιλογή στον πίνακα εμφανίζει κατάλληλο μήνυμα
 else {messageBox.infoBox("Δεν έχετε επιλέξει εγγραφή προς επεξεργασία");}
        
    }//GEN-LAST:event_editActionPerformed

    private void delActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delActionPerformed
        // ενέργειες που εκτελούντε όταν πατάμε διαγραφή
        int s=jTable1.getSelectedRow();
        if (s>=0) //Εάν έχει γίνει επιλογή από τον πίνακα
            {               
                RolePermission rp = list1.get(jTable1.convertRowIndexToModel(s));
                list1.remove(rp); 
                em.remove(rp);           
            }
        else
            {  //Εάν δεν έχει γίνει επιλογή στον πίνακα
                messageBox.infoBox("Δεν έχει γίνει επιλογή Εγγραφής");
            } 
    }//GEN-LAST:event_delActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditRoleForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cancel;
    private javax.swing.JButton Save;
    private javax.swing.JButton del;
    private javax.swing.JButton edit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private java.util.List<RolePermission> list1;
    private javax.swing.JButton neo;
    private javax.persistence.Query query1;
    private avenue.RoleBoxRenderer roleBoxRenderer1;
    private model.UserRole userRole2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    UserRole userRole1 , ur ;
    RolePermission rp;
    boolean readOnly;
    int s;
}
